"""This file contains the rule to generate a license map for node modules"""

def _node_modules_licenses_impl(ctx):
    """Wrapper for the license-map-generator command-line tool"""

    node_modules_args = ctx.actions.args()
    node_modules_args.add_all(ctx.files.node_modules)
    node_modules_args.use_param_file("%s", use_always = True)

    licenses_texts_args = ctx.actions.args()
    licenses_texts_args.add_all(ctx.files.licenses_texts)
    licenses_texts_args.use_param_file("%s", use_always = True)

    ctx.actions.run(
        executable = ctx.executable._license_map_generator,
        arguments = [ctx.file.licenses_config.path, node_modules_args, licenses_texts_args, ctx.outputs.json.path],
        outputs = [ctx.outputs.json],
        inputs = depset([ctx.file.licenses_config] + ctx.files.licenses_texts, transitive = [ctx.attr.node_modules.files]),
    )

# Rule to run license-map-generator.ts
# node_modules - label of npm workspace in the format @npm//:node_modules
# The output contains information about licenses for the workspace.
# licenses_texts is a list of shared licenses
# For details - see comments in the
# tools/node_tools/node_modules_licenses/license-map-generator.ts file
node_modules_licenses = rule(
    implementation = _node_modules_licenses_impl,
    attrs = {
        "node_modules": attr.label(mandatory = True),
        "licenses_texts": attr.label_list(allow_files = True, mandatory = True),
        "licenses_config": attr.label(allow_single_file = True, mandatory = True),
        "_license_map_generator": attr.label(
            default = Label("//tools/node_tools/node_modules_licenses:license-map-generator-bin"),
            executable = True,
            cfg = "host",
        ),
    },
    outputs = {
        "json": "%{name}.json",
    },
)
